import {
	getStrCount
} from '@/common/string-utils.js'
import {
	getRandomId
} from '@/common/common.js'
export default {
	name: 'index',
	props: {
		chartTitle: {
			type: String
		},
		valueList: {
			//图例里面Value列配置
			type: Array,
			default: () => {
				// 只有百分比的值
				return [{
					key: 'percent'
				}]
				// 包含百分比标题的值
				// return [{ title: '百分比', key: 'percent' }]
				// 包含两列Value值和标题
				// return [
				//   { title: '销量', key: 'value' },
				//   { title: '同比', key: 'percent' }
				// ]
			}
		},
		chartData: {
			type: Array,
			default: () => {
				return [{
						name: '一日游',
						value: 20,
						percent: '20%'
					},
					{
						name: '两日游',
						value: 16,
						percent: '16%'
					},
					{
						name: '三日游',
						value: 5,
						percent: '5%'
					}
				]
			}
		}
	},
	data() {
		return {
			randomId: getRandomId(),
			pieColor: ['#4472EF', '#3BB9F8', '#42D5DE', '#FDD005', '#38B289', '#B0E105']
		}
	},
	watch: {
		chartData: {
			//深度监听，可监听到对象、数组的变化
			handler(val, oldVal) {
				// console.log('PieChart-chartData')
				this.updateChartData()
			},
			deep: true
		},
		valueList: {
			handler(val, oldVal) {
				val.forEach(valItem => {
					let titleLine = getStrCount(valItem.title, '\n') + 1
					// console.log('titleLine', titleLine)
					valItem.titleTop = '-' + titleLine * 15 + 'px'
					valItem.titleH5 = valItem.title.replace(/\n/g, '<br>')
				})
			},
			deep: true
		}
	},
	created() {},
	computed: {},
	mounted() {},
	methods: {
		updateChartData() {
			let echarts = require('echarts')
			let myChart = echarts.init(document.getElementById(this.randomId))
			myChart.clear()
			let mOption = {
				color: this.pieColor,
				series: [{
					type: 'pie',
					clockwise: false, //饼图的扇区是否是顺时针排布
					radius: ['40%', '60%'],
					center: ['25%', '50%'],
					itemStyle: {
						borderColor: '#ffffff',
						borderWidth: 2
					},
					label: {
						show: false,
						position: 'center',
						formatter: '{b}\n {d}%',
						lineHeight: 20
					},
					emphasis: {
						label: {
							show: true,
							color: '#000',
							fontSize: 12
						}
					},
					data: this.chartData
				}]
			}
			myChart.setOption(mOption)
			this.setAutoTouch(myChart)
		},
		setAutoTouch(myChart) {
			let index = 0
			myChart.dispatchAction({
				type: 'highlight',
				seriesIndex: 0,
				dataIndex: 0
			})
			myChart.on('mouseover', function(e) {
				if (e.dataIndex != index) {
					myChart.dispatchAction({
						type: 'downplay',
						seriesIndex: 0,
						dataIndex: index
					})
				}
			})
			myChart.on('mouseout', function(e) {
				index = e.dataIndex
				myChart.dispatchAction({
					type: 'highlight',
					seriesIndex: 0,
					dataIndex: e.dataIndex
				})
			})
		}
	}
}
